"""
@Time    : 2019/10/4 14:22
@Author  : CcH
"""

import cv2
import os
from tqdm import tqdm

mouth_cascade = cv2.CascadeClassifier('haarcascade_mcs_mouth.xml')
def picture2mouth(imagePath,filepath,min_scale):
    flag = 0
    img = cv2.imread(imagePath)
    # img = cv2.resize(img,(256,256))
    if type(img) != str:
        mouth = mouth_cascade.detectMultiScale(img, 1.1, min_scale)
        if len(mouth):
            maxxy = -1
            for (x, y, w, h) in mouth:
                # 设置人脸宽度大于128像素，去除较小的人脸
                # 扩大图片，可根据坐标调整
                if w >= 50 and h >= 50:
                    xy = x * y
                    X = int(x * 0.8)
                    W = min(int((x + w) * 1.2), img.shape[1])
                    Y = int(y * 0.6)
                    H = min(int((y + h)), img.shape[0])

                    # f = cv2.resize(img[Y:H, X:W], (64, 64))
                    f = cv2.resize(img[Y:H, X:W], (100, 50))
                    if xy > maxxy:
                        cv2.imwrite(filepath, f)
                        maxxy = xy
                        flag = 1
    return flag

if __name__ == '__main__':
    # 数据集路径
    path = r"D:\XW_Bank\LipRecognition\train\lip_train"
    # 数据保存路径
    write_path = r"D:\XW_Bank\LipRecognition\train\lip_100_50_train"
    for pct_id in tqdm(os.listdir(path)):
        input_path = path + "//" + pct_id
        write_path_new = write_path + "//" + pct_id
        isExists = os.path.exists(write_path_new)
        # 判断结果
        if not isExists:
            # 如果不存在则创建目录
            os.makedirs(write_path_new)
        for pnm in os.listdir(input_path):
            picture_pt = input_path + "//" + pnm
            flag = picture2mouth(picture_pt,write_path_new+'//'+pnm,20)
            if flag == 0:
                flag_10 = picture2mouth(picture_pt, write_path_new + '//' + pnm, 10)
                if flag_10 == 0:
                    picture2mouth(picture_pt, write_path_new + '//' + pnm, 1)


